<?php 
namespace app\api\controller;

use common\model\sell66\User;
use common\steamauth\LightOpenID;
use common\steamauth\SteamConfig;
use app\api\ApiController;
use common\service\AuthService;
use common\service\UserService;
use common\libs\Curl;
use common\libs\StringHelper;
use common\service\AppService;
use common\service\SteamUtilService;
use common\service\QueueService;

class  Steamauth extends ApiController{
	
	public static $redirectUrls = [
		'default'=>'/@/site/home',
		'commission'=>'',
	];
	/**
	 * @api {get} /steamauth/login steam授权登陆
	 * @apiVersion 1.0.0
	 * @apiName login
	 * @apiGroup steamauth
	 *
	 * @apiDescription  steam授权登陆接口
	 *
	 * @apiParam {String} redirectUrl 登陆完成后跳转的页面，默认首页
	 *
	 * @apiError 20000 请求参数错误
	 *
	 * @apiErrorExample Response (example):
	 *  {
	 *		code: 99999,
	 *		msg: "请求成功",
	 *		data: {
	 *			redirectUrl: "https://steamcommunity.com/openid/login?openid"
	 *		}
	 *	}	
	 */
	public function login($invite_token = ""){
		$steamauth = SteamConfig::getConfig();
		$openid = new LightOpenID($steamauth['domainname'],$steamauth['loginpage']);
		if(!$openid->mode) {
			$openid->identity = 'https://steamcommunity.com/openid';
			$url = $openid->authUrl();
			header('Location: '.$url);
			exit;
		} elseif ($openid->mode == 'cancel') {
			return $this->errorMessage("User has canceled authentication!");
		} else {
			if($openid->validate()) {
				$isInviteUser = false;
				$steamid = $openid->getSteamId() ;
				$userSteam = UserService::getInstance()->getUserInfoBySteamId($steamid);

                //获取steam信息并修改到数据表中
                $time = 1;
                while ($time < 3) {
                    $url = 'https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=79C29405EFF8086937D964FB5698435B&steamids='.$steamid;
                    $result = Curl::http_get($url);
                    $content = json_decode($result, true);

                    if (!empty($content)) {
                        break;
                    }
                    $time++;
                }

                if (!isset($content['response']['players'])) {
                    $openid->identity = 'https://steamcommunity.com/openid';

                    $url = $openid->authUrl();

                    header('Location: ' . $url);
                    exit;
                }

                if (empty($content['response']['players'])) {
                    $openid->identity = 'https://steamcommunity.com/openid';

                    $url = $openid->authUrl();

                    header('Location: ' . $url);
                    exit;
                }
                
                $content = current($content['response']['players']);

                $steamUserInfo['steam_steamid'] = $content['steamid'];
                $steamUserInfo['steam_communityvisibilitystate'] = empty($content['communityvisibilitystate']) ? 0 : $content['communityvisibilitystate'];

                $content['personaname'] = $this->filterEmoji($content['personaname']);
                $steamUserInfo['steam_personaname'] = $this->fixEncoding($content['personaname']);
                $steamUserInfo['steam_avatarIcon'] = empty($content['avatar']) ? "" : $content['avatar'];
                $steamUserInfo['steam_avatarmedium'] = empty($content['avatarmedium']) ? "" : $content['avatarmedium'];
                $steamUserInfo['steam_avatarfull'] = empty($content['avatarfull']) ? "" : $content['avatarfull'];

                if (isset($content['realname'])) {
                    $steamUserInfo['steam_realname'] = is_array($content['realname']) ? json_encode($content['realname']) : $content['realname'];
                    $steamUserInfo['steam_realname'] = $this->filterEmoji($steamUserInfo['steam_realname']);
                    $steamUserInfo['steam_realname'] = $this->fixEncoding($steamUserInfo['steam_realname']);
                } else {
                    $steamUserInfo['steam_realname'] = "";
                }
                if (empty($userSteam)) {
                    $userSteam = UserService::getInstance()->createUserBySteam($steamUserInfo);
                    $isInviteUser = UserService::getInstance()->addInviteLog($invite_token, $userSteam['user_id']);
                }else{
                    $userSteam = UserService::getInstance()->updateUserBySteam($userSteam['user_id'],$steamUserInfo);
                }

                QueueService::getInstance()->setAdapter('UserSteamJob')->userSteamJob($userSteam['steam_id']);

				$userInfo = AuthService::getInstance()->saveSteamLoginInfo($userSteam);
				$token = $userInfo['access_token'];
				if(empty($isInviteUser)){
					$redirectUrl = self::$redirectUrls['default'];
				}elseif(!empty(self::$redirectUrls[$isInviteUser])){
					$redirectUrl = self::$redirectUrls[$isInviteUser];
				}else{
					$redirectUrl = self::$redirectUrls[$isInviteUser];
				}
                // $url = $steamauth['redirectpage'].'?redirectUrl='.$redirectUrl.'&access_token='.$token;
                 $url = $steamauth['redirectpage'].'?access_token='.$token;
                if(isset($userInfo['user_id']) && !empty($userInfo['user_id'])){
                    $userId = $userInfo['user_id'];
                    // 更新用户登录时间
                    User::refreshLoginTimeByUserId($userId);
                    UserService::getInstance()->createUserLoginLog($userSteam['user_id']);
                }
				if (!headers_sent()) {
					header('Location: '.$url);
					exit;
				} else {
					return $this->redirect($url);
				}
			}
		}
	}

	function fixEncoding($in_str)
	{
		$cur_encoding = mb_detect_encoding($in_str) ;

		if($cur_encoding == "UTF-8" && mb_check_encoding($in_str,"UTF-8")) {
			return $in_str;
		} else {
			return utf8_encode($in_str);
		}
	}

	function filterEmoji($str)
	{
		$str = preg_replace_callback(
		'/./u',
		function (array $match) {
			return strlen($match[0]) >= 4 ? '' : $match[0];
		},
		$str);

		return $str;
	}

    protected function request_curl($url)
    {
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_PROXY, 'tmo:happy998@128.199.144.99:1080');
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        //打印获得的数据
        return $output;
    }

    // 仅用于获取steam授权登录链接
    public function getSteamUrl(){
        $steamauth = SteamConfig::getConfig();
        $openid = new LightOpenID($steamauth['domainname']);
        $openid->identity = 'https://steamcommunity.com/openid';
        return $this->successJson(array("redirectUrl"=>$openid->authUrl()));
    }
	
	
	/**
	 * @api {get} /steamauth/checklogin 验证是否成功授权
	 * @apiVersion 1.0.0
	 * @apiName checklogin
	 * @apiGroup steamauth
	 *
	 * @apiDescription  验证是否成功授权
	 *
	 * @apiError 20000 请求参数错误
	 *
	 * @apiErrorExample Response (example):
	 * {
	 *	code: 99999,
	 *	msg: "请求成功",
	 *	data: {
	 * 		user_id: 10,
	 *		steam_id: "76561198376305817",
	 *		created_time: false,
	 *		updated_time: false,
	 *		communityvisibilitystate: 3,
	 *		avatarfull: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/ff/ff063e6af49a1245c3507a994c1504ab9ae8aa6c_full.jpg",
	 *		personaname: "Groot0617",
	 *		profileurl: "http://steamcommunity.com/id/groot0617/",
	 *		avatar: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/ff/ff063e6af49a1245c3507a994c1504ab9ae8aa6c.jpg",
	 *		realname: "Groot",
	 *		avatarmedium: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/ff/ff063e6af49a1245c3507a994c1504ab9ae8aa6c_medium.jpg"
	 *		}
	 *	}
	 */
	public function checkLogin(){
		$user = AuthService::getInstance()->verifyToken();
		if(empty($user)){
            return $this->errorMessage(BAD_ACCESS_TOKEN_NO,BAD_ACCESS_TOKEN_ERROR);
        }
        return $this->successJson($user);
	}	
}